package com.yikes.srb.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yikes.srb.common.result.PageResult;
import com.yikes.srb.common.utils.object.BeanUtils;
import com.yikes.srb.leadingModle.form.lendItemReturn.LendItemReturnAddForm;
import com.yikes.srb.leadingModle.form.lendItemReturn.LendItemReturnEditForm;
import com.yikes.srb.leadingModle.form.lendItemReturn.LendItemReturnQuery;
import com.yikes.srb.leadingModle.vo.LendItemReturnVO;
import com.yikes.srb.mapper.LendItemMapper;
import com.yikes.srb.mapper.LendMapper;
import com.yikes.srb.mapper.LendReturnMapper;
import com.yikes.srb.pojo.entity.Lend;
import com.yikes.srb.pojo.entity.LendItem;
import com.yikes.srb.pojo.entity.LendItemReturn;
import com.yikes.srb.mapper.LendItemReturnMapper;
import com.yikes.srb.pojo.entity.LendReturn;
import com.yikes.srb.service.LendItemReturnService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yikes.srb.service.UserBindService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 标的出借回款记录表 服务实现类
 * </p>
 *
 * @author guanrong.yin
 * @since 2024-12-03
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LendItemReturnServiceImpl extends ServiceImpl<LendItemReturnMapper, LendItemReturn> implements LendItemReturnService {

    private final UserBindService userBindService;

    private final LendItemMapper lendItemMapper;

    private final LendMapper lendMapper;

    private final LendReturnMapper lendReturnMapper;

    @Override
    public PageResult<LendItemReturnVO> listPage(LendItemReturnQuery query) {

        Page<LendItemReturn> page = lambdaQuery()
                .eq(ObjectUtil.isNotNull(query.getInvestAmount()), LendItemReturn::getInvestAmount, query.getInvestAmount())
                .eq(ObjectUtil.isNotNull(query.getCurrentPeriod()), LendItemReturn::getCurrentPeriod, query.getCurrentPeriod())
                .eq(ObjectUtil.isNotNull(query.getReturnMethod()), LendItemReturn::getReturnMethod, query.getReturnMethod())
                .eq(ObjectUtil.isNotNull(query.getIsOverdue()), LendItemReturn::getIsOverdue, query.getIsOverdue())
                .eq(ObjectUtil.isNotNull(query.getStatus()), LendItemReturn::getStatus, query.getStatus())
                .page(Page.of(query.getPageNum(), query.getPageSize()));

        List<LendItemReturnVO> bean = BeanUtils.toBean(page.getRecords(), LendItemReturnVO.class);
        return PageResult.build(page.getTotal(), page.getPages(), bean);
    }

    @Override
    public LendItemReturnVO infoId(Long id) {

        LendItemReturn lendItemReturn = getById(id);
        LendItemReturnVO bean = BeanUtils.toBean(lendItemReturn, LendItemReturnVO.class);
        return bean;

    }

    @Override
    public void create(LendItemReturnAddForm form) {

        LendItemReturn bean = BeanUtils.toBean(form, LendItemReturn.class);
        save(bean);
    }

    @Override
    public void edit(LendItemReturnEditForm form) {

        LendItemReturn bean = BeanUtils.toBean(form, LendItemReturn.class);
        updateById(bean);
    }

    @Override
    public void del(Long id) {

        baseMapper.deleteById(id);
    }

    @Override
    public List<LendItemReturnVO> selectByLendId(Long lendId, Long userId) {

        List<LendItemReturn> list = lambdaQuery().eq(LendItemReturn::getLendId, lendId).eq(LendItemReturn::getInvestUserId, userId).list();

        return BeanUtils.toBean(list, LendItemReturnVO.class);
    }

    /**
     * 添加还款明细
     * @param lendReturnId
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public List<Map<String, Object>> addReturnDetail(Long lendReturnId) {
        //获取还款记录
        LendReturn lendReturn = lendReturnMapper.selectById(lendReturnId);
        //获取标的信息
        Lend lend = lendMapper.selectById(lendReturn.getLendId());

        //根据还款id获取回款列表
        List<LendItemReturn> lendItemReturnList = this.selectLendItemReturnList(lendReturnId);
        List<Map<String, Object>> lendItemReturnDetailList = new ArrayList<>();
        for(LendItemReturn lendItemReturn : lendItemReturnList) {
            LendItem lendItem = lendItemMapper.selectById(lendItemReturn.getLendItemId());
            String bindCode = userBindService.getBindCodeByUserId(lendItem.getInvestUserId());

            Map<String, Object> map = new HashMap<>();
            //项目编号
            map.put("agentProjectCode", lend.getLendNo());
            //出借编号
            map.put("voteBillNo", lendItem.getLendItemNo());
            //收款人（出借人）
            map.put("toBindCode", bindCode);
            //还款金额
            map.put("transitAmt", lendItemReturn.getTotal());
            //还款本金
            map.put("baseAmt", lendItemReturn.getPrincipal());
            //还款利息
            map.put("benifitAmt", lendItemReturn.getInterest());
            //商户手续费
            map.put("feeAmt", new BigDecimal("0"));

            lendItemReturnDetailList.add(map);
        }
        return lendItemReturnDetailList;
    }

    /**
     * 根据还款计划id获取对应的回款计划列表
     * @param lendReturnId
     * @return
     */
    @Override
    public List<LendItemReturn> selectLendItemReturnList(Long lendReturnId) {

        return lambdaQuery().eq(LendItemReturn::getLendReturnId, lendReturnId).list();
    }
}
